//
//  ESSpotlightSeacrchManager.m
//  EasyStyle
//
//  Created by FK on 16/1/8.
//  Copyright © 2016年 FK. All rights reserved.
//

#import "ESSpotlightSeacrchManager.h"
#import <CoreSpotlight/CoreSpotlight.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import "SDWebImageManager.h"
#import "SDImageCache.h"
#import "ESWeixinNetResult.h"

@interface ESSpotlightSeacrchManager ()
@property (nonatomic,strong) NSOperationQueue *operationQueue;

@end

@implementation ESSpotlightSeacrchManager

+ (instancetype)sharedInstance{
    static ESSpotlightSeacrchManager *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (instance == nil) {
            instance = [[self alloc] init];
            instance.operationQueue = [NSOperationQueue new];
            
        }
    });
    return instance;
}

- (void)addRecord:(id)aRecord{
    
    if (aRecord!= nil) {
        @synchronized(self.operationQueue){
            [self.operationQueue addOperationWithBlock:^{
                
                CSSearchableItem *gsItem = [self constructWithObject:aRecord];
                
                if (gsItem != nil) {
                    [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:@[gsItem] completionHandler:nil];
                }
            }];
        }
    }
}

- (void)addRecords:(NSArray *)records{
    
    if (records.count != 0) {
        
        @synchronized(self.operationQueue){
            [self.operationQueue addOperationWithBlock:^{
                
                NSArray *realRecords = [NSArray arrayWithArray:records];
                
                NSMutableArray *gsItems = [NSMutableArray array];
                
                for (int i = 0; i < realRecords.count; i++) {
                    id item = realRecords[i];
                    CSSearchableItem *gsItem = [self constructWithObject:item];
                    if (gsItem != nil) {
                        [gsItems addObject:gsItem];
                    }
                }
                if (gsItems.count != 0) {
                    [[CSSearchableIndex defaultSearchableIndex] indexSearchableItems:gsItems completionHandler:nil];
                }
            }];
        }
    }
}

- (void)removeRecord:(id)aRecord{
    
    if (aRecord!=nil) {
        NSString *identifier = [self identifierWith:aRecord];
        @synchronized(self.operationQueue){
            [self.operationQueue addOperationWithBlock:^{
                
                [[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:@[identifier] completionHandler:nil];
            }];
        }
    }
}

- (void)removeRecords:(id)records{
    
    if (records!=nil) {
        @synchronized(self.operationQueue){
            [self.operationQueue addOperationWithBlock:^{
                NSArray *realRecords = [NSArray arrayWithArray:records];
                
                NSMutableArray *items = [NSMutableArray array];
                
                for (int i = 0; i < realRecords.count; i++) {
                    id record = realRecords[i];
                    NSString *identifier = [self identifierWith:record];
                    
                    if (identifier) {
                        [items addObject:identifier];
                    }
                }
                [[CSSearchableIndex defaultSearchableIndex] deleteSearchableItemsWithIdentifiers:items completionHandler:nil];
            }];
        }
    }
}

- (NSString *)identifierWith:(id)object{
    
    NSString *retId = nil;
    if ([object isKindOfClass:[WxNewsObject class]]) {
        WxNewsObject *wxAriticle = (WxNewsObject *)object;
        retId = [NSString stringWithFormat:@"%@.%@",ES_SpotlightDomain_WeChat,wxAriticle.newsID];
    }
    return retId;
}

- (CSSearchableItem *)constructWithObject:(id)object{
    
    CSSearchableItem *retObj = nil;
    
    if ([object isKindOfClass:[WxNewsObject class]]) {
        WxNewsObject *wxAriticle = (WxNewsObject *)object;
        CSSearchableItemAttributeSet *attributeSet = [[CSSearchableItemAttributeSet alloc] initWithItemContentType:(NSString *)kUTTypeImage];
        
        attributeSet.title = wxAriticle.title;
        attributeSet.contentDescription = AppName;
        attributeSet.keywords = @[(wxAriticle.title.length!=0)?wxAriticle.title:@"",(wxAriticle.source.length!=0)?wxAriticle.source:@"",(wxAriticle.mark.length!=0)?wxAriticle.mark:@"",@"生活",AppName];
        
//        if (wxAriticle.type == 1 || wxAriticle.type == 2 ) {
        
            NSString *key = [[SDWebImageManager sharedManager] cacheKeyForURL:[NSURL URLWithString:wxAriticle.firstImg]];
            UIImage *lastPreviousCachedImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:key];
            
            if (lastPreviousCachedImage!= nil) {
                attributeSet.thumbnailData = UIImagePNGRepresentation(lastPreviousCachedImage);
            }
//        }
        
        NSString *uniqueIdentifier = [self identifierWith:object];
        
        retObj = [[CSSearchableItem alloc] initWithUniqueIdentifier:uniqueIdentifier domainIdentifier:ES_SpotlightDomain_WeChat attributeSet:attributeSet];
    }
    return retObj;
}

- (void)handleWithUserActivity:(NSUserActivity *)userActivity{
    
    NSString *identifier = userActivity.userInfo[CSSearchableItemActivityIdentifier];
    
    if (identifier.length!=0) {
        
        if ([identifier hasPrefix:ES_SpotlightDomain_WeChat]) {
            
            identifier =  [identifier componentsSeparatedByString:@"."].lastObject;
            
//            WxNewsObject *article = [[SGWXArticleManager sharedInstance] getArticleWithMd5:identifier];
//            
//            //            if (article == nil) {
//            //                article = [[[SGCollectManager sharedInstance] queryCollectItemWithMd5:identifier] weixinAriticle];
//            //            }
//            
//            if (article != nil) {
//                [[SGWXOpenManager sharedInstance] handleAction:article source:@"generalsearch"];
//                //                [[NSNotificationCenter defaultCenter] postNotificationName:SGOpenWeixinArticleNotification object:article userInfo:@{@"source":@"generalsearch"}];
//            }else{
//                [[iToast makeText:@"该文章不存在~~"] show];
//            }
            
        }
    }
    
}

@end

@implementation ESSpotlightSearchItem


@end

